import axios from 'axios'
import type { Method } from 'axios'
import type { ApiRes } from '../types/Data'
import store from '../store/index'
import {getToken,cleUserMessage} from '../store/actionDemo'
import {createBrowserHistory} from 'history'

const instance = axios.create({
    baseURL: process.env.REACT_APP_BASEURL
})

instance.interceptors.request.use(
    config => {
        const token = store.getState().counter.token
        if (token) {
            config.headers.token =token
        }
        return config
    },
    error => { // 当发生错误时，执行该部分代码
        return Promise.reject(error)
    }
)

instance.interceptors.response.use(
    function (response) {
        console.log(response.data.code);
        
        if (response.data.code === 401) {
            console.log(6666);
            store.dispatch(cleUserMessage({}))
            createBrowserHistory().push('/login')
            // window.location.href='/#/login'
        }
        return response.data
    },
    function (error) {
        return error
    })

const request = <T>({ url, method, data }: {
    url: string
    method?: Method
    data?: object
}) => {
    return instance<any, ApiRes<T>>({
        url,
        method,
        [method?.toUpperCase() === 'GET' ? 'params' : 'data']: data
    })
}

export default request